import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Typography,
  Grid,
  Card,
  CardContent,
  CardActionArea,
  TextField,
  InputAdornment,
  IconButton,
  Chip,
  Pagination,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Paper,
} from '@mui/material';
import {
  Search as SearchIcon,
  LocalOffer as TagIcon,
  Category as CategoryIcon,
  Visibility as VisibilityIcon,
} from '@mui/icons-material';
import axios from 'axios';

const HomePage = () => {
  const navigate = useNavigate();
  const [knowledges, setKnowledges] = useState([]);
  const [categories, setCategories] = useState([]);
  const [tags, setTags] = useState([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [filters, setFilters] = useState({
    categoryId: '',
    tagId: '',
    importance: '',
  });

  const pageSize = 9;

  useEffect(() => {
    // 获取分类列表
    const fetchCategories = async () => {
      try {
        const response = await axios.get('/api/category?all=true');
        setCategories(response.data);
      } catch (error) {
        console.error('获取分类失败:', error);
      }
    };

    // 获取标签列表
    const fetchTags = async () => {
      try {
        const response = await axios.get('/api/tag');
        setTags(response.data);
      } catch (error) {
        console.error('获取标签失败:', error);
      }
    };

    fetchCategories();
    fetchTags();
  }, []);

  useEffect(() => {
    // 获取知识条目列表
    const fetchKnowledges = async () => {
      setLoading(true);
      try {
        let url = `/api/knowledge?page=${page}&page_size=${pageSize}`;
        
        // 添加过滤条件
        if (filters.categoryId) url += `&category_id=${filters.categoryId}`;
        if (filters.tagId) url += `&tag_id=${filters.tagId}`;
        if (filters.importance) url += `&importance=${filters.importance}`;
        
        // 添加搜索条件
        if (searchTerm) url += `&search=${encodeURIComponent(searchTerm)}`;

        const response = await axios.get(url);
        setKnowledges(response.data.data);
        setTotalPages(Math.ceil(response.data.total / pageSize));
      } catch (error) {
        console.error('获取知识条目失败:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchKnowledges();
  }, [page, filters, searchTerm]);

  const handleSearch = (e) => {
    e.preventDefault();
    setPage(1); // 重置页码
  };

  const handleFilterChange = (e) => {
    const { name, value } = e.target;
    setFilters(prev => ({
      ...prev,
      [name]: value
    }));
    setPage(1); // 重置页码
  };

  const handlePageChange = (event, value) => {
    setPage(value);
  };

  const handleKnowledgeClick = (id) => {
    navigate(`/knowledge/${id}`);
  };

  // 获取分类名称
  const getCategoryName = (categoryId) => {
    const category = categories.find(cat => cat.id === categoryId);
    return category ? category.name : '未分类';
  };

  return (
    <Box sx={{ flexGrow: 1 }}>
      <Paper elevation={0} sx={{ p: 2, mb: 3 }}>
        <Typography variant="h4" gutterBottom>
          知识库
        </Typography>
        <Box component="form" onSubmit={handleSearch} sx={{ mb: 3 }}>
          <Grid container spacing={2} alignItems="center">
            <Grid item xs={12} sm={6} md={4}>
              <TextField
                fullWidth
                variant="outlined"
                placeholder="搜索知识..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                InputProps={{
                  endAdornment: (
                    <InputAdornment position="end">
                      <IconButton type="submit" edge="end">
                        <SearchIcon />
                      </IconButton>
                    </InputAdornment>
                  ),
                }}
              />
            </Grid>
            <Grid item xs={12} sm={6} md={2}>
              <FormControl fullWidth variant="outlined">
                <InputLabel>分类</InputLabel>
                <Select
                  name="categoryId"
                  value={filters.categoryId}
                  onChange={handleFilterChange}
                  label="分类"
                >
                  <MenuItem value="">全部</MenuItem>
                  {categories.map((category) => (
                    <MenuItem key={category.id} value={category.id}>
                      {category.name}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} sm={6} md={2}>
              <FormControl fullWidth variant="outlined">
                <InputLabel>标签</InputLabel>
                <Select
                  name="tagId"
                  value={filters.tagId}
                  onChange={handleFilterChange}
                  label="标签"
                >
                  <MenuItem value="">全部</MenuItem>
                  {tags.map((tag) => (
                    <MenuItem key={tag.id} value={tag.id}>
                      {tag.name}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} sm={6} md={2}>
              <FormControl fullWidth variant="outlined">
                <InputLabel>重要性</InputLabel>
                <Select
                  name="importance"
                  value={filters.importance}
                  onChange={handleFilterChange}
                  label="重要性"
                >
                  <MenuItem value="">全部</MenuItem>
                  <MenuItem value="3">★★★</MenuItem>
                  <MenuItem value="2">★★</MenuItem>
                  <MenuItem value="1">★</MenuItem>
                </Select>
              </FormControl>
            </Grid>
          </Grid>
        </Box>

        <Grid container spacing={3}>
          {knowledges.map((knowledge) => (
            <Grid item xs={12} sm={6} md={4} key={knowledge.id}>
              <Card sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
                <CardActionArea onClick={() => handleKnowledgeClick(knowledge.id)}>
                  <CardContent sx={{ flexGrow: 1 }}>
                    <Typography gutterBottom variant="h6" component="div" noWrap>
                      {knowledge.title}
                    </Typography>
                    <Typography variant="body2" color="text.secondary" sx={{ mb: 2, height: '3em', overflow: 'hidden', textOverflow: 'ellipsis', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' }}>
                      {knowledge.content.replace(/<[^>]*>/g, '')}
                    </Typography>
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mt: 1 }}>
                      <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
                        <Chip
                          size="small"
                          icon={<CategoryIcon fontSize="small" />}
                          label={getCategoryName(knowledge.category_id)}
                          variant="outlined"
                        />
                        {knowledge.tags && knowledge.tags.slice(0, 2).map((tag) => (
                          <Chip
                            key={tag.id}
                            size="small"
                            icon={<TagIcon fontSize="small" />}
                            label={tag.name}
                            variant="outlined"
                          />
                        ))}
                      </Box>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                        <VisibilityIcon fontSize="small" color="action" />
                        <Typography variant="caption" color="text.secondary">
                          {knowledge.views}
                        </Typography>
                      </Box>
                    </Box>
                    <Box sx={{ mt: 1 }}>
                      {Array(knowledge.importance).fill().map((_, i) => (
                        <span key={i} role="img" aria-label="star">★</span>
                      ))}
                    </Box>
                  </CardContent>
                </CardActionArea>
              </Card>
            </Grid>
          ))}
        </Grid>

        {knowledges.length === 0 && !loading && (
          <Box sx={{ textAlign: 'center', py: 4 }}>
            <Typography variant="body1" color="text.secondary">
              没有找到相关知识条目
            </Typography>
          </Box>
        )}

        {totalPages > 1 && (
          <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
            <Pagination 
              count={totalPages} 
              page={page} 
              onChange={handlePageChange} 
              color="primary" 
            />
          </Box>
        )}
      </Paper>
    </Box>
  );
};

export default HomePage;